from rest_framework import serializers
from .models import Patient, Diagnosis
from apps.doctor.models import DiagnosisTemplate

class CaseInsensitiveChoiceField(serializers.ChoiceField):
    def to_internal_value(self, data):
        if data:
            data = str(data).lower()
        return super().to_internal_value(data)

class PatientSerializer(serializers.ModelSerializer):
    status = CaseInsensitiveChoiceField(choices=Patient.STATUS_CHOICES)
    
    class Meta:
        model = Patient
        fields = [
            'id', 'name', 'gender', 'age', 'phone', 'address',
            'id_number', 'medical_record_no', 'medical_history', 'allergies', 
            'registration_time', 'doctor', 'status', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']

class DiagnosisSerializer(serializers.ModelSerializer):
    patient_name = serializers.CharField(source='patient.name', read_only=True)
    doctor_name = serializers.CharField(source='doctor.get_full_name', read_only=True)

    class Meta:
        model = Diagnosis
        fields = [
            'id', 'patient', 'patient_name', 'doctor', 'doctor_name',
            'chief_complaint', 'present_illness', 'past_history',
            'allergy_history', 'physical_examination', 'diagnosis',
            'treatment_plan', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at'] 